import React from 'react';
import {Menu, Layout} from 'antd';
import {inject, observer} from 'mobx-react';
import {Icon} from '../../../components';
import {ToolHistory} from '../../../utils';

import './index.scss';

/**
 * 左侧菜单组件
 * 属性：
 * type：布局类型。类型：'view'|'home'|'menu'|'tab'。
 */
@inject('store')
@observer
export default class Sider extends React.Component {
  //默认值
  static defaultProps = {
    className: ''
  };

  constructor(props) {
    super(props);
    this.state = {
      collapsed: false //是否收缩菜单
    };
  }

  render() {
    let {collapsed} = this.state;

    return (
      <Layout.Sider className="g-layout-sider" theme="light" collapsed={collapsed} width={240}>
        {this.renderFold()}
        {this.renderMenu()}
      </Layout.Sider>
    );
  }

  /**
   * 折叠图标
   */
  renderFold() {
    let {collapsed} = this.state;
    return (
      <div className={collapsed ? 'fold-collapse' : 'fold'} onClick={() => this.setState({collapsed: !collapsed})}>
        <Icon
          className={collapsed ? 'fold-icon-collapse' : 'fold-icon'}
          type={collapsed ? 'menu-unfold' : 'menu-fold'}
        />
        <span className={collapsed ? 'fold-title-collapse' : 'fold-title'}>收起菜单</span>
      </div>
    );
  }

  /**
   * 左侧菜单
   */
  renderMenu() {
    let {routerData, routerMenu} = this.props.store;
    if (routerMenu) routerMenu = routerMenu[this.props.type];
    //注意：routerData只能维护菜单项的key，所以菜单的key使用defaultOpenKeys属性
    const {keyGroup, keyItem} = routerData || {};
    //由于菜单的key使用defaultOpenKeys属性，所以需要keyGroup非空，才能正常展示
    if (!keyGroup) return;

    return (
      <Menu mode="inline" defaultOpenKeys={[keyGroup]} selectedKeys={[keyItem]}>
        {this.renderMenuList(routerMenu)}
      </Menu>
    );
  }

  /**
   * 菜单列表
   */
  renderMenuList(list) {
    let result = [];
    list.forEach((item) => {
      let {children, label, icon} = item;
      let list2 = [];
      children.forEach((item2) => {
        if (!item2.view) return;

        let viewItem = (
          <Menu.Item key={item2.keyItem} onClick={() => ToolHistory.href(item2.path)}>
            {item2.label}
          </Menu.Item>
        );
        list2.push(viewItem);
      });
      let viewMenu = (
        <Menu.SubMenu
          key={item.keyGroup}
          title={
            <span>
              <Icon type={icon} />
              <span>{label}</span>
            </span>
          }
        >
          {list2}
        </Menu.SubMenu>
      );
      result.push(viewMenu);
    });
    return result;
  }
}
